var service = new EbeimService();
var service2 = new EbeimService2();
var $allPage = 1/*,$onceUp = false, $onceDown = true*/;

var onceKey = true;
var pathNodes = [];
var pathSet = {
		async: {
            enable: true,
            url: "/rest/system/dirs",
            autoParam: ["path"],
            dataType: "json",
            dataFilter:function(treeId, parentNode, responseData){
            	var nodes = [];
                getPathTree(responseData,nodes);
                return nodes;
            	
            },
            type:"get"
        },
        view: {
            fontCss: getFont,
            dblClickExpand: false,
            showLine: false
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        callback: {
            onClick: pathClick
        }
    };

function setNId(nid,value){
	if(nid.indexOf('DS-')==0){
		if(!service.nids) service.nids = {};
		service.nids[nid] = value;
	}
}

var htmlOfProcess = {}
function setWhole(dsId,version,path){
	var processBarOfBottom = $("#processBarOfBottom");
	var key  = $("#processBarOfBottom .whole")[0].getAttribute('nid');
	if(key==''){
		htmlOfProcess['def'] = processBarOfBottom.html();	
	}else{
		htmlOfProcess[key] = processBarOfBottom.html();
	}
	
	processBarOfBottom.empty();
	if(htmlOfProcess[dsId]){
		processBarOfBottom.html(htmlOfProcess[dsId]);
	}else{
		processBarOfBottom.html(htmlOfProcess['def']);
		$(".whole").attr("nid",dsId);
		$(".whole").attr("id","bartd"+dsId);
		$(".whole").attr("version",version);
		$(".whole").attr("path",path);
	}
}
$(function(){
	var jlist = $("#j-list"); 
	var jreset = $("#j-reset"); 
	var jbackupList = $("#j-backupList");
	var jupLevel = $("#j-upLevel");
	var jbackupMore = $("#j-backupMore");
	var jbackupInp = $("#j-backupInp");
	var jback = $("#j-back");
	var jaddress = $("#j-address");
	var jwhole = $("#j-whole");
	
	$("#w-page").keyup(function(){
		if(event.keyCode == 13){
			var flag = $("#w-page").val();
			page(flag);
		}
	});
	
	var setting;
	var zPath;
	var zNodes =[];
	var upLevel = "";
	var key = true;
	var terminalId = plugin.GetQueryString("terminalId");
	var dsId = plugin.GetQueryString("dsId");
	
	var tpl = (function(){
        var tpl = {};
        $("script[type='text/ysmart']").each(function(){
            var t = $(this);
            tpl[t.attr("data-name")] = t.html();
        });
        return tpl;
    })();
	var searchVar = {
		pageSize:15,
		startPorts:1,
		endPorts:4,
		dsId: dsId,
		version:plugin.GetQueryString("version"),
		path:plugin.GetQueryString("path"),
		status:plugin.GetQueryString("status")
    }
	
	setWhole(searchVar.dsId, searchVar.version, searchVar.path);
	
	var backupVar = {
		backupLog:{dsId : dsId,status:0},
		pages:{
			startPos : 1,
			pageSize : 5
		}
    }
	
	setting = {
		async: {
            enable: true,
            url: "/rest/datasource/menu",
            autoParam: ["id","type","version","path","dsId","root"],
            dataType: "json",
            dataFilter:function(treeId, parentNode, responseData){
            	if(responseData.code == "200"){
            		var nodes = [];
                	getTree(responseData.list,nodes);
                	return nodes;
            	}else{
            		plugin.msgtip({type: "e",msg: responseData.message});
            	}
            	
            },
            type:"get"
        },
        view: {
            fontCss: getFont,
            dblClickExpand: false,
            showLine: false
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        callback: {
            onClick: onClick,
            onExpand:function(event, treeId, treeNode){
            	var treeObj = $.fn.zTree.getZTreeObj(treeId);
            	var unableNodes = treeObj.getNodesByParam("unable", true);
    			if (unableNodes.length>0) {
    				for(var i in unableNodes){
    					$("#"+unableNodes[i].tId+"_ico").css({"cursor":"default"});
    				}		
    			}
            	if(key){
            		key = false;
	            	var dsNodes = treeObj.getNodesByParam("id", dsId);
	            	if (dsNodes.length>0) {
	            		treeObj.selectNode(dsNodes[0]);	
	            		var p = dsNodes[0].getParentNode();
		            	zPath = dsNodes[0].name;
		            	while (p != null){
		            		zPath = p.name + " / " + zPath;
		        	    	p = p.getParentNode();
		            	}
		            	jaddress.html(zPath);
	        		}
            	}
            }
        }
    };
	
	/*$(".folder-scroll").scroll(function(){
		
		if($allPage <= searchVar.startPorts){
			return false;
		}
		var t = $(this);
		if((t.scrollTop() + t.height()) >= $("#j-table").height()){
			var tr = $("#j-list tr");
			searchVar.startPorts++;
			getList();
		};
	});*/
	
	var $topHistory = 0;
	$(".folder-scroll").scroll(function(e){
		var t = $(this);
		if(t.scrollTop() > $topHistory){
			$topHistory = t.scrollTop();
			if((t.scrollTop() + t.height()) >= $("#j-table").height()){
				if($allPage > searchVar.endPorts){
					searchVar.startPorts++;
					searchVar.endPorts++;
					getList("append");
				}
				/*if(!$onceDown && $allPage >= (searchVar.startPorts+4)){
					$onceDown = true;
					$onceUp = false;
					searchVar.startPorts += 4;
					getList("append");
				}*/
			};
		}else{
			$topHistory = t.scrollTop();
			if(t.scrollTop() <= 0){
				if(searchVar.startPorts > 1){
					searchVar.startPorts--;
					searchVar.endPorts--;
					getList("prepend");
				}
				/*if(!$onceUp && (searchVar.startPorts - 4) >= 1){
					$onceDown = false;
					$onceUp = true;
					searchVar.startPorts -= 4;
					getList("prepend");
				}*/
			};
		}
	});
	
	jbackupMore.bind("click",function(){
		$(this).css("display","none");
		backupVar.pages.pageSize = 0;
		getBackuplogs();
	})
	
	jreset.bind("click",function(){
		var version = $(".j-backupItem").eq(0).attr("data-version");
		searchVar.startPorts = 1;
		searchVar.endPorts = 4;
		searchVar.version = version;
		backupVar.pages.pageSize = 5
		jbackupMore.css("display","block");
		getList();
		getBackuplogs();
	})
	
	jwhole.bind("click",function(){
		var dsId = $(".whole").attr("nid");
		var version = $(".whole").attr("version");
		var path = $(".whole").attr("path");
		directors(dsId,path.split("\\").join("\\\\"),version,'',dsId,dsId)
	})
	
	jupLevel.bind("click",function(){
		if(upLevel==""){
			setWhole(searchVar.dsId, searchVar.version, "/");
			plugin.msgtip({type: "i",msg: "已为当前数据源的最高层"});
			return false;
		}
		var parent = "/";
		var idx = upLevel.lastIndexOf("\\");
		if(idx!=-1){
			parent = upLevel.substring(0,idx);
		}
		
		setWhole(searchVar.dsId, searchVar.version, parent==""?"/":parent);
		
		upLevel = parent;
		searchVar.startPorts = 1;
		searchVar.endPorts = 4;
		searchVar.path = parent;
		var idz = zPath.lastIndexOf("\/");
		zPath = zPath.substring(0,idz);
		jaddress.html(zPath);
		getList();
	})
	
	jback.bind("click",function(){
		window.location.href = "/web/html/client-list.html?dsType=0&isSelf="+ plugin.GetQueryString("isSelf");
		//history.back(-1);
	})
	
	jbackupList.delegate(".j-backupItem","click",function(){
		var t = $(this), version = t.attr("data-version");
		searchVar.startPorts = 1;
		searchVar.endPorts = 4;
		searchVar.version = version;
		jbackupInp.val(t.html());
		getList();
	})
	
	jlist.delegate(".j-listItem","click",function(){
		var t = $(this), path = t.attr("data-path");
		
		setWhole(searchVar.dsId, searchVar.version, path);
		
		searchVar.startPorts = 1;
		searchVar.endPorts = 4;
		searchVar.path = path;
		upLevel = path;
		var idz = path.lastIndexOf("\\");
		path = path.substring(idz,path.length).split("\\").join("\/");
		zPath = zPath + path;
		jaddress.html(zPath);
		getList();
	})
	
	$("#ab-dir").keydown(function(){
		if (event.keyCode == 13) { 
			var val = $(this).val();
			val = val.replace(/\//g, "\\");
			if(val.charAt(val.length - 1) == ":"){
				val = val+"\\";
			}
			$(this).val(val);
			selectRecoveryPath(val);
		}
	})
	
	$(".w-dir-list").delegate(".j-path","click",function(){
		var val = $(this).attr("data-path");
		selectRecoveryPath(val);
	})
	
	$(".filechangelog-ul").delegate(".j-recoveryBtn","click",function(){
		var version = $(this).attr("data-version");
		setHideVersion(version);
		service.openFolder({},function(json){
			if(json.code == "200"){
				if(!json.path){
					return false
				}
				$("#h_abDir").val(json.path);
				recovery(version);
			}else{
				plugin.msgtip({type: "e", msg: json.msg});
			}
		})
	})
	
	service.getMenuTree({type:"0"},function(json){
		if(json.code == "200"){
			getTree(json.list,zNodes);
			for(var i in zNodes){
				zNodes[i].unable = true;
			}
			$.fn.zTree.init($("#treeDemo"), setting, zNodes);
			var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
			var unableNodes = treeObj.getNodesByParam("unable", true);
			if (unableNodes.length>0) {
				for(var i in unableNodes){
					$("#"+unableNodes[i].tId+"_a").css({"cursor":"default","text-decoration":"none"});
					$("#"+unableNodes[i].tId+"_ico").css({"cursor":"default"});
				}		
			}
			var terminalNodes = treeObj.getNodesByParam("id", terminalId);
			if (terminalNodes.length>0) {
				treeObj.expandNode(terminalNodes[0], true ,false,true,true);		
			}
			getList();
		}else{
			plugin.msgtip({type: "e",msg: json.message});
		}
	});
	
	var getList = function(callback){
		service.getFileList(searchVar,function(json){
			if(json.code == 500){
				plugin.msgtip({type: "i",msg: json.message});
				getBackuplogs();
				jlist.html("");
				return false
			}
			$allPage = json.allPage;
			for(var i in json.list){
				json.list[i].fileSize = fileSizeTransfer(json.list[i].fileSize);
				json.list[i].dsId = searchVar.dsId;
				json.list[i].version = searchVar.version;
				if(json.list[i].type == "文件"){
					var idx = json.list[i].name.lastIndexOf(".");
					var suffix = json.list[i].name.substring(idx+1,json.list[i].name.length);
					switch(suffix.toLowerCase()){
						case "doc" : case "docx" : 
							json.list[i].icoType = "folder-doc";
							break;
						case "xls" : case "xlsx" : 
							json.list[i].icoType = "folder-xls";
							break;
						case "ppt" : case "pptx" : 
							json.list[i].icoType = "folder-ppt";
							break;
						case "bmp" : case "gif" : case "jpg" : case "jpeg" : case "png" : case "psd" : case "svg" : case "ico" : case "tga" : case "ai" : 
							json.list[i].icoType = "folder-img";
							break;
						case "avi" : case "rmvb" : case "rm" : case "asf" : case "divx" : case "mpg" : case "mpeg" : case "mpe" : case "wmv" : case "mp4" : case "mkv" : case "vob" : case "flv" : 
							json.list[i].icoType = "folder-mov";
							break;
						case "html" : case "xhtml" : case "xml": 
							json.list[i].icoType = "folder-html";
							break;
						case "apk": 
							json.list[i].icoType = "folder-apk";
							break;
						case "rar" : case "zip" : case "cab" : case "arj" : case "lzh" : case "ace" : case "7z" : case "tar" : case "gzip" : case "uue" : case "bz2" : case "jar" : case "iso" : case "z" : 
							json.list[i].icoType = "folder-rar";
							break;
						case "mp3" : case "wma" : case "rm" : case "wav" : case "midi" : 
							json.list[i].icoType = "folder-mp3";
							break;
						case "txt" : 
							json.list[i].icoType = "folder-txt";
							break;
						case "pdf" : 
							json.list[i].icoType = "folder-pdf";
							break;
						case "exe" : 
							json.list[i].icoType = "folder-exe";
							break;
						default :
							json.list[i].icoType = "folder-file";
						
					}
				}
				/*json[i].path = json[i].path.split("\\").join("\\\\");*/
			}
			
			jlist.html(plugin.ysmart(tpl.list, json.list));
			if(callback == "append"){
				var H = $(".folder-scroll").scrollTop() - 705;
				$(".folder-scroll").scrollTop(H);
			}else if(callback == "prepend"){
				var H = 705;
				$(".folder-scroll").scrollTop(H);
			}else{
				$(".folder-scroll").scrollTop("0");
				getBackuplogs();
			}
			
			/*if(searchVar.startPorts == 1){
				$(".folder-scroll").scrollTop("0");
				jlist.html(plugin.ysmart(tpl.list, json.list));	
			}else{
				jlist.append(plugin.ysmart(tpl.list, json.list));	
			}*/
			
//			getDownloadProcessBar();
		});
	}
	var getBackuplogs = function(callback){
		service.getBackuplogs(backupVar,function(json){
			var list = "";
			/*if(json.list.page.totalRecord <= 5){
				jbackupMore.css("display","none");
			}else{
				jbackupMore.css("display","block");
			}*/
			
			if(json.list.objList.length==0)
				{
				jbackupInp.val("");
				}
			
			for(var i = 0; i < json.list.objList.length; i++){
				var btime = json.list.objList[i].beginTime;
				if (btime == 0) {
					btime = "---"
				} else {
					btime = getTimeStr(btime);
				}
			 if(json.list.objList[i].versionMajor == searchVar.version){
					jbackupInp.val(btime);
				}
				list = list+"<li class='j-backupItem j-getVal' data-version='"+json.list.objList[i].versionMajor+".0'>"+btime+"</li>"
			}
			jbackupList.html(list);
		})
	}
	
	function onClick(e,treeId, treeNode) {
		if(!treeNode.dsId){
			$("#"+treeNode.tId+"_a").removeClass("curSelectedNode");
			return false;
		}
		searchVar.startPorts = 1;
		searchVar.endPorts = 4;
		searchVar.dsId = treeNode.dsId;
		searchVar.version = treeNode.version;
		searchVar.path = treeNode.path;
		setWhole(searchVar.dsId, searchVar.version, searchVar.path);
		
		if(treeNode.path == "/"){
			upLevel = "";
		}else{
			upLevel = treeNode.path;
		}
		backupVar.backupLog.dsId = treeNode.dsId;
		backupVar.pages.pageSize = 5
		jbackupMore.css("display","block");
    	var p = treeNode.getParentNode();
    	zPath = treeNode.name;
    	while (p != null){
    		zPath = p.name + " / " + zPath;
	    	p = p.getParentNode();
    	}
    	jaddress.html(zPath);
		getList();
   }
	
	$W = $(window).width();
	$H = $(window).height();
	w = $(".window").width(); 
	h = $(".window").height();
	$(".window").css("top",(($H-h)/2)-80);
	$(".window").css("left",($W-w)/2);
//	setInterval("getDownloadProcessBar()", 2500);
	setInterval("getDownloadProcessBarAll()", 2500);
	
	
})
    
function getFont(treeId, node) {
    return node.font ? node.font : {};
}

function getTree(json,nodes){
	for(var i = 0;i<json.length; i++){
		var data = {};
		data.id = json[i].id;
		data.name = json[i].name;
		data.pId = json[i].pid;
		data.type = (parseInt(json[i].type) + 1)+"";
		data.version = json[i].version;
		data.path = json[i].path;
		data.root = json[i].root;
		data.dsId = json[i].dsId;
		data.isParent = true;
		if(json[i].type == "0"){
			data.iconSkin = "sty01"
		}else if(json[i].type == "1"){
			data.iconSkin = "sty02"
		}else{
			data.iconSkin = "sty03"
		}
		nodes[i] = data;
	}
	getDownloadProcessBarAll();
	countByType($downloadFailed);
}

function fileSizeTransfer(size){
	var fileSize = size;
	if(size/1024 > 1){
		fileSize = size/1024.0;
		fileSize = fileSize.toFixed(2);
		fileSize += "KB";
	}else{
		fileSize += "B";
	}
	if(size/(1024*1024) > 1){
		fileSize =size/(1024.0*1024);
		fileSize = fileSize.toFixed(2);
		fileSize += "MB";
	}
	if(size/(1024*1024*1024) > 1){
		fileSize = size/(1024.0*1024*1024);
		fileSize = fileSize.toFixed(2);
		fileSize += "GB";
	}
	return fileSize;
}

//2015年11月13日09:07:01
function directors(dsId,path,version,name,bartd_id,nid){
	
//	if(service.nids && service.nids[nid]){
//		plugin.msgtip({type:"e",msg:"正在恢复。。。"});
//		return;
//	}
	
	
	$("#h_dsId").val(dsId);
	$("#h_path").val(path);
	$("#h_bartd_id").val(bartd_id);
	if(nid){
		$("#h_nid").val(nid);
	}
	service.getBackuplogs(getBackupWrapper(dsId), backupLogCB);
	
}
function files(dsId,path,version,name,bartd_id,nid){
	$("#h_dsId").val(dsId);
	$("#h_bartd_id").val(bartd_id);
	$("#h_path").val(path+"\\"+name);
	if(nid){
		$("#h_nid").val(nid);
	}
	var service1 = new EbeimService();
	service1.getFileChangeLog({
		dsId:dsId,
		path:encodeURIComponent(path),
		version:version,
		name:encodeURIComponent(name)
	}, fileChangeLogBC);
}

var fileChangeLogBC = function (data) {
    var json = data;
	var list = json.list;
	var size = list.length;
	var content = "";
	for (var i = 0; i < (list.length>5?5:list.length); i++) {
		var obj = list[i];
		if(obj.result=="fail"){
			size --;
			continue;
		}
		content = content
		+"<li>"
		+"<span style='float:left;'><button class='btn j-recoveryBtn' data-version = '"+obj.version+"'>恢复至</button></span>"
		/*+"<span style='float:left;'><button onclick='selectRecoveryPath(\"\"),setHideVersion(\""+obj.version+"\")' class='btn'>恢复至</button></span>"*/
		+"<span style='float:right;'>"+getTimeStr(obj.logTime)+"</span>"
		+"</li>";
	}
	if(size==0){
		content = content
		+"<li style='text-align:center'>暂无可恢复的版本!</li>";
	}
	$(".filechangelog-ul").html(content);
	showDialog("versionWindow");
	
};

function getBackupWrapper(dsId) {
	var backupLog = {
		dsId : dsId,
		status:0
	}
	var pages = {
		startPos : 0,
		pageSize : 5
	}
	var json = {};
	json["backupLog"] = backupLog;
	json["pages"] = pages;

	return json;
}

var backupLogCB = function(data){
	var list = data.list.objList;
	var size = list.length;
	var content = "";
	for (var i = 0; i < size; i++) {
		obj = list[i];
		content = content
		+"<li>" 
		+"<span style='float:left;'><button class='btn j-recoveryBtn' data-version = '"+obj.versionMajor+".0'>恢复至</button></span>"
		/*+"<span style='float:left;'><button onclick='selectRecoveryPath(\"\"),setHideVersion(\""+obj.versionMajor+".0\")' class='btn'>恢复至</button></span>"*/
		+"<span style='float:right;'>"+getTimeStr(obj.beginTime)+"</span>"
		+"</li>";
	}
	if(size==0){
		content = content
		+"<li style='text-align:center'>暂无可恢复的版本!</li>";
	}
	$(".filechangelog-ul").html(content);
	showDialog("versionWindow");
};
function setHideVersion(version){
	$("#h_version").val(version);
}
function selectRecoveryPath(path){
	$(".window").css("display","block");
	$(".shadowDiv").css("display","block");
	while(path.charAt(path.length - 1) == "\\" && path.charAt(path.length - 2) != ":"){
		path = path.substring(0,path.length-1)
	}
	$("#ab-dir").val(path);
	service.getSystemDirs(
		{
			path:path,
			action:"recovery"
		}, 
		selectRecoveryPathCB
	);
	/*var abDir = $("#ab-dir").val();
	if(abDir!=""){
		$("#ab-dir").html(abDir+"\\"+path);
		service.getSystemDirs({
			path:abDir+"\\"+path,
			action:"recovery"
		}, selectRecoveryPathCB);
	}else{
		$("#ab-dir").html(path);
		service.getSystemDirs({
			path:path,
			action:"recovery"
		}, selectRecoveryPathCB);
	}*/
}
var selectRecoveryPathCB = function(data){
	if(data.code == "500"){
		plugin.msgtip({type: "e", msg: "系统找不到该路径！"});
		return false
	}
	var json = data;
	var content = "";
	if(onceKey == true){
		onceKey = false;
		getPathTree(data,pathNodes);
		$.fn.zTree.init($("#pathTree"), pathSet, pathNodes);
	}
	for (var i = 0; i < json.length; i++) {
		var name = json[i].name;
		
		var showName = name;
		if(showName.indexOf("\Desktop")!=-1){
			showName = "桌面"
		    name = name.split("\\").join("\\\\");
		}
		content = content +
		"<li class='j-path' title='"+name+"' data-path='"+json[i].absolutePath+"'><a href='javascript:;'><p>"+showName+"</p></a></li>";
	}
	$(".w-dir-list ul").html(content);
}
function selectParentPath(path){
	var abDir = $("#ab-dir").val();
	var idx = abDir.lastIndexOf("\\");
	if(abDir.charAt(abDir.length - 2) != ":" && idx!=-1){
		abDir = abDir.substring(0,idx);
		if(abDir.charAt(abDir.length - 1) == ":"){
			abDir = abDir+"\\";
		}
		$("#ab-dir").val(abDir);
    	service.getSystemDirs({
    		path:abDir
    	}, selectRecoveryPathCB);
	}else{
		$("#ab-dir").val("");
		service.getSystemDirs({
			path:""
		}, selectRecoveryPathCB);
	}
}

function getFont(treeId, node) {
    return node.font ? node.font : {};
}
function getPathTree(json,nodes){
	var j = 0;
	for(var i = 0;i<json.length; i++){
		var data = {};
		if(json[i].isParent){
			if(json[i].name.indexOf("\Desktop")!=-1){
				data.name = "桌面"
			}else{
				data.name = json[i].name;
			}
			data.path = json[i].absolutePath;
			data.isParent = json[i].isParent;
			data.iconSkin = "path";
			
			nodes[j] = data;
			j++;
		}	
	}
}

function pathClick(e,treeId, treeNode) {
	selectRecoveryPath(treeNode.path);
}

function confirmDir(){
	var version = $("#h_version").val();
	recovery(version);
}
function cancelDir(){
	clearDateAndWindow();
}

function recovery(version,dynamicCode){
	var dsId = $("#h_dsId").val();
	var path ="/"+$("#h_path").val();
	/*var abDir = $("#ab-dir").val();*/
	var abDir = $("#h_abDir").val();
	var nid = $("#h_nid").val();
	
	setNId(nid, true);
	
	if(abDir == ""){
		plugin.msgtip({type:"e",msg:"请选择下载目录"});
		return;
	}
	$("#recoveyBtn").attr("disabled","disabled");
	service.recoveryFile({
		dsId:dsId,
		path:encodeURIComponent(path),
		version:version,
		dynamicCode:dynamicCode,
		abDir:encodeURIComponent(abDir),
		nid:nid
	},  function(data){
		if(data.code=="200" || data.code==200){
			
		}else{
			setNId(nid,false);
		}
		recoveryCB(data);
	});
}

var recoveryCB = function(data){
	$("#recoveyBtn").removeAttr("disabled");
	var json = data;
	if(json.code=="200" || json.code==200){
		
		clearDateAndWindow();
		
		var td_id = $("#h_bartd_id").val();
    	$("#"+td_id).parent().find("td").find(".tipspan").html("等待链接...");
   		var content = ""
   		+"<div style='width:120px;height:20px;border:solid 1px #B8C86C;margin:0 auto;position:relative;'>"
   		+"<div id='processbar' style='width:0px;height:20px;background:#B8C86C;'></div>"
   		+"<div class='r-info' style='line-height:20px;text-align:center;position:absolute;top:0;left:0;width:100%;height:20px;'>下载进度:<span id='percentage' style='color:green'>0.00%</span></div>"
   		+"</div>";
   		
   		var td_id = $("#h_bartd_id").val();
   		if(!$("#"+td_id).hasClass("delDownloadBtn")){
   			$("#"+td_id).html(content);
   		}
   		
	 }else{
		 dsSecurityRankCheck(json,json.message);
	 }
}

function clearDateAndWindow(){
	$("#dynamicCode").val("");
	$("#ab-dir").val("");
	hideDialog("versionWindow");
	closeCodeWindow();
	onceKey = true;
	$(".window").css("display","none");
	$(".shadowDiv").css("display","none");
}

function setDynamicCode(){
	var dynamicCode = $("#dynamicCode").val().replace(/(^\s+)|(\s+$)/g,"");
	if(dynamicCode == ""){
		 plugin.msgtip({type: "e", msg: "动态验证码不能为空!"});
		return;
	}
	var h_whichGetModel = $("#h_whichGetModel").val();
	if(h_whichGetModel=="handBackup"){
		var dsSecurityRank = $("#h_dsSecurityRank").val();
		handBackup($dsId, dsSecurityRank, dynamicCode);
	}else{
		var version = $("#h_version").val();
		recovery(version,dynamicCode);
	}
	
}

function getDownloadProcessBar() {

	var ids = "";
	$(".bartd").each(function() {
		ids += $(this).attr("nid") + ",";
	});
	if (ids.length > 0) {
		ids = ids.substring(0, ids.length - 1);
		service.getDownloadProcessBar({
			nids:ids
		}, processbarCB);
//		service.deleteDownloadProcessBar({
//			nids:ids
//		}, delProcessbarCB);
	}
}


var processbarCB = function(data){
	var json = data;
	var list = json.beans;
	if(list.length<=0){
		$(this).parent().find("td").find(".tipspan").html("");
		$(this).html("下载完成!");
		return ;
	}
	for (var i = 0; i < list.length; i++) {
		var bean = list[i];
		$(".bartd").each(function(){
			var nid = $(this).attr("nid");
			if (nid == bean.nid) {
				setNId(nid, true);
				var count = bean.count;
				var total = bean.total;
				var fileSum = bean.fileSum;
				var okSum = bean.okSum;
				var errorSum = bean.errorSum;
				var percent = (count/total)*100;
				
				var isWhole = $(this).attr("class");
				if(isWhole.indexOf("whole")!=-1){
					$(this).css("display","block");
				}
				
				var content = ""
			   		+"<div style='width:100px;height:20px;border:solid 1px #B8C86C;margin:0 auto;position:relative;'>"
			   		+"<div id='processbar' style='width:0px;height:20px;background:#B8C86C;'></div>"
			   		+"<div class='r-info' style='line-height:20px;text-align:center;position:absolute;top:0;left:0;width:100%;height:20px;'>下载进度:<span id='percentage' style='color:green'>0.00%</span></div>"
			   		+"</div>";
				$(this).html(content);
				
				if(count >= total || okSum+errorSum>=fileSum){
					$(this).parent().find("td").find(".tipspan").html("");
					$(this).html("下载完成!");
					setNId(nid, false);
//    					if(bean.nid.indexOf('DS-')!=0){ 
//    						setTimeout(function(){
//    							$("#j-reset").click();
//    						}, 3000);
//    					}
					if(total==0){
						service.deleteDownloadProcessBarByNid({nid:nid}, function(data){;})
					}
				}else if(count == -1 || errorSum==fileSum){
					setNId(nid, false);
					$(this).find(".r-info").html("<font color='red'>下载失败！</font>");
					service.deleteDownloadProcessBarByNid({
						nid:nid
					}, function(data){;});
				}else{
	    			$(this).parent().find("td").find(".tipspan").html("正在下载...");
	    			$(this).find("#processbar").css("width",percent+"%");
	    			$(this).find("#percentage").html((Math.floor(percent*100)/100)+"%");
				}
			}
		});
	}
}
var delProcessbarCB = function(data) {
	var json = data;
}

function showDownloadBar(){
	showDialog('downloadWindow');
}

function getDownloadProcessBarAll(){
	service.getDownloadProcessBarAll({
		dsType:0
	}, function(data){
		var beans = data.beans;
		var downloadProcessbarContent = "";
		var jtag = $("#download_process_tag").siblings(".j-tag");
		if(beans.length > 0){
			$("#download_process_tag").css("display","block");
			$("#download_process_tag").html(beans.length);
			jtag.css("display","block");
			jtag.html(beans.length);
			jtag.stop();
			jtag.animate({padding:"8px",top:"-10px",right:"-5px",opacity:"0"},500,function(){
				$(this).css({padding:"3px",top:"-5px",right:"0",display:"none",opacity:"1"});
			})
		}else{
			$("#download_process_tag").css("display","none");
		}
		for(var i = 0; i<beans.length; i++){
			var bean = beans[i];
			var fs = bean.fileSum - (bean.okSum + bean.errorSum);
			var p = (Math.floor((bean.count * 100 / bean.total)*100)/100).toFixed(2);
			var info = "";
			var btn = "";
			var barColor = "green";
			if(p == 0 && fs>0){
				info="连接中..."
			}else if(bean.errorSum>=bean.fileSum && bean.errorSum >0){
				info="<font color='red'>下载失败!</font>";
				barColor = "#999";
				btn = "<a class='delDownloadBtn' id='"+bean.nid+"' href='javascript:deleteDownloadBar(\""+bean.nid+"\");'>删除</a>";
				$(".j-delete").css("display","inline-block");
				$(".j-undelete").css("display","none");
			}else if(p >= 100 || fs<=0){
				info = "下载完成!";
				p = 100;
				btn = "<a class='delDownloadBtn' id='"+bean.nid+"' href='javascript:deleteDownloadBar(\""+bean.nid+"\");'>删除</a>";
				$(".j-delete").css("display","inline-block");
				$(".j-undelete").css("display","none");
			}else{
				info = "下载进度:"+ p + "%";
			}
			downloadProcessbarContent = downloadProcessbarContent
			+"<tr>"
			+"	<td><nobr title='"+bean.name+"' style='max-width:200px;display:inline-block;overflow:hidden;text-overflow:ellipsis;'>"+bean.name+"</nobr></td>"
			+"	<td width='150px' style='font-size:12px;text-align:center;'>"+getTimeStr(bean.createtime)+"</td>"
			+"	<td width='150px' style='text-align:center;' dsid='"+bean.id+"' class='processTD'>"
			
			+"<div class='processbar' style='background:#999;width:100px;height:20px;position:relative;margin:0 auto;'>"
			+ "<div class='bar' style='height:20px;background:"+barColor+";width:"+p+"%;'></div>"
			+ "<div class='info' style='font-size:12px;width:100px;height:20px;color:#fff;position:absolute;top:0;left:0'>"
			+	info
			+" </div>"
			+"</div>"
			
			+"</td>"
			+"	<td width='60px;' style='text-align:center;'>"+btn+"</td>"
			+"</tr>";
		}
		$("#downloadProcessbarTB").html(downloadProcessbarContent);
	});
}
function deleteDownloadBar(nid){
	if(!nid){
		nid = "";
		$(".delDownloadBtn").each(function(){
			nid += $(this).attr("id")+",";
		});
		if(nid.length>0){
			nid = nid.substring(0,nid.length-1);
		}
	}
	if(!nid || nid.length==0){
		plugin.msgtip({type:"e",msg:"还没可以清除的数据!"});
		return;
	}
	service.deleteDownloadProcessBar({
		nids:nid
	}, function(data){
		//TODO
		$(".j-delete").css("dispaly","none");
		$(".j-undelete").css("dispaly","inline-block");
	},function(data){
	});
}
